package jp.co.piratealliance.pirateAllianceWeb.web.servlet;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jp.co.piratealliance.pirateAllianceWeb.common.log.DebugLogger;
import jp.co.piratealliance.pirateAllianceWeb.common.util.StringUtils;
import jp.co.piratealliance.pirateAllianceWeb.def.SystemConf;

/**
 * copyright pirate alliance team 2014
 *
 * @author xuwei
 *
 */
public class ImageServlet extends HttpServlet
{
	/**
	 *
	 */
	private static final long serialVersionUID = 1L;

	/**
	 * doget
	 *
	 * @param request
	 *            HttpServletRequest
	 * @param response
	 *            HttpServletResponse
	 * @throws IOException
	 *             文件读写异常
	 * @throws ServletException
	 *             ServletException
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException
	{

		this.loadData(request, response);

	}

	/**
	 * dopost
	 *
	 * @param request
	 *            HttpServletRequest
	 * @param response
	 *            HttpServletResponse
	 * @throws IOException
	 *             文件读写异常
	 * @throws ServletException
	 *             ServletException
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException
	{
		doGet(request, response);
	}

	/**
	 * 関連の初期化処理を行う。
	 *
	 * @param request
	 *            HttpServletRequest
	 * @param response
	 *            HttpServletResponse
	 * @throws IOException
	 *             文件读写异常
	 * @throws ServletException
	 *             ServletException
	 */
	public void loadData(HttpServletRequest request,
			HttpServletResponse response) throws IOException, ServletException
	{
		request.setCharacterEncoding("UTF-8");

		String filePath = request.getParameter("PATH");

		String fileName = StringUtils.getFileName(filePath);//SystemConf.getImageRootDir() + filePath;

//		String suffix = null;
//		int index = filePath.lastIndexOf(".");
//		if (index > 0)
//		{
//			suffix = filePath.substring(index + 1);
//		}
//		else
//		{
//			suffix = "unknown";
//		}

//		if ("pdf".equalsIgnoreCase(suffix))
//		{
//			response.setContentType("application/pdf");
//		}
//		else
//		{
//			response.setContentType("image/" + suffix);
//		}
		response.setHeader("Content-Disposition", "inline; filename="
				+ fileName);

		String realPath = StringUtils.linkFilePath(SystemConf.getImageRootDir(), filePath);
		InputStream in = this.getImageSource(realPath);
		if (in == null)
		{
			DebugLogger.log("File is not exists! " + realPath);
			return;
		}

		int length = getFileSize(in);
		response.setContentLength(length);
		ServletOutputStream output = response.getOutputStream();

		// 输入缓冲流
		BufferedInputStream bis = new BufferedInputStream(in);
		// 输出缓冲流
		BufferedOutputStream bos = new BufferedOutputStream(output);

		int bufferSize = 1024;

		byte ioBuf[] = new byte[bufferSize];
		do
		{
			int chunkLen = bis.read(ioBuf);
			if (chunkLen <= 0)
			{
				break;
			}
			bos.write(ioBuf, 0, chunkLen);
		}
		while (true);
		bis.close();
		bos.flush();// 清空输出缓冲流
		bos.close();
		// }
		// in.close();
		output.close();
	}

	private int getFileSize(InputStream in)
	{
		int size = 0;
		try
		{
			size = Integer.parseInt(String.valueOf(in.available()));
		}
		catch (NumberFormatException e)
		{
			//ErrorLogger.log(e);
		}
		catch (IOException e)
		{
			//ErrorLogger.log(e);
		}
		return size;
	}

	/**
	 * 根据系统文件相对路径获取画像资源，如果指定的相对路径不存在，则使用系统提供的默认画像
	 *
	 * @param relativePath
	 *            画像相对路径
	 * @return 画像文件的读写类
	 */
	private InputStream getImageSource(String relativePath)
	{

		String path = relativePath;
		File file = new File(path);
		if (!file.exists() || !file.isFile())
		{
			path = getServletContext().getRealPath("images/blank.bmp");

			file = new File(path);
		}
		try
		{
			return new FileInputStream(file);
		}
		catch (FileNotFoundException e)
		{
			return null;
		}

	}
}
